/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode} head
 * @param {number} k
 * @return {ListNode}
 */
var reverseKGroup = function(head, k) {
      if (!head || k <= 1) return head;
    
    // 计算链表长度
    let length = 0;
    let current = head;
    while (current) {
        length++;
        current = current.next;
    }
    const dummy = new ListNode(0);
    dummy.next = head;
    let prev = dummy;
    let curr = head;
    
    // 处理需要翻转的组
    for (let i = 0; i < Math.floor(length / k); i++) {
        // 翻转k个节点
        for (let j = 0; j < k - 1; j++) {
            const next = curr.next;
            curr.next = next.next;
            next.next = prev.next;
            prev.next = next;
        }
        prev = curr;
        curr = curr.next;
    }
    
    return dummy.next;
};
